/**
 * Transmit content-body中面页跳转时前端传递参数。其中参数的传递分为url参数传递和localStrong参数传递。
 * 参数传递到第二个页面时数据会保存到window.param对象中
 * 参数
 * 	url： url参数
 * 	unUrl： localStrong参数
 * 	其他参数默认重utl中传递
 * 	back: 返回时取数据，保留前页的数据。
 * 使用：
 * 	$.Transmit({url: {id: 123, name: "yye"}, unUrl: {adr: "da"}, tel: 123254345, back: {index: "2"}});
 * 	取参数时：
 * 	alert(window.param.id);
 * 	alert(window.param.adr);
 * 	alert(window.param.tel);
 * 	window.back.pop();
 */
define(['jquery'], function($) {
	function Transmit() {

	}
	
	Transmit.prototype.init = function(opt) {
		this.param = opt || {url: {}, unUrl: {}};
		this.urlParam = this.param.url;
		this.unUrlParam = this.param.unUrl;
		window.back = window.back || [];
		window.back.push(this.param.back || {});
		delete this.param.url;
		delete this.param.unUrl;
		delete this.param.back;
		this.urlParam = $.extend(this.urlParam, this.param);
		this.saveParam();
	};
	
	Transmit.prototype.saveParam = function() {
		this.clearParam();
		var urlStr = this.getStringParam(this.urlParam);
		window.location.href =  window.location.href + urlStr;
		var unUrlStr = this.getStringParam(this.unUrlParam);
		window.localStorage.setItem("Transmit.param", unUrlStr);
	};
	
	Transmit.prototype.getParam = function() {
		var p = {};
		var urlP = this.getObjectParam(window.location.href.substring(window.location.href.indexOf("#") + 1));
		var unUrlP = this.getObjectParam(window.localStorage.getItem("Transmit.param"));
		p = $.extend(urlP, unUrlP);
		return p;
	};
	
	Transmit.prototype.clearParam = function() {
		window.location.href = window.location.href.substring(0, window.location.href.indexOf("#")) + "#";
		window.localStorage.removeItem("Transmit.param");
	};
	
	Transmit.prototype.getStringParam = function(obj) {
		var value = "";
		for(var key in obj) {
			value += key + "=" + encodeURIComponent(obj[key]) + "&";
		}
		value = value.substr(0, value.length - 1);
		return value;
	};
	
	Transmit.prototype.getObjectParam = function(str) {
		if(str == "" || str == null || str == undefined) {
			return {};
		} 
		var obj = {};
		var strArr = str.split("&");
		for(var i = 0; i < strArr.length; i++) {
			if(str == "" || str == null || str == undefined) {
				continue;
			}
			var arr = strArr[i].split("=");
			obj[arr[0]] = decodeURIComponent(arr[1]);
		}
		return obj;
	}
	
	var transmit = new Transmit();
	
	$.Transmit = function(opt) {
		transmit.init(opt);
	}
	
	$.Transmit_getParam = function() {
		return transmit.getParam();
	}
});